package com.api.cdfortis.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.cdfortis.dto.*;
import com.api.cdfortis.prop.AppProp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微问诊对接工具类
 */
@Component
public class WwzUtil {
    /**
     * 接口返回结果的变量名
     */
    public final static String RETURN_CODE = "returnCode";

    /**
     * 接口token
     */
    public static String TOKEN = "";

    @Autowired
    private AppProp appProp;

    /**
     * 5.6 手机端一笔订单多张处方记录查询
     * @param orderId 订单编号
     * @return
     */
    public ResultDto<List> getPresFromOrderNo(String orderId){
        JSONObject paramJson = new JSONObject();
        paramJson.put("appid", appProp.getAppid());
        paramJson.put("token", getToken());
        paramJson.put("orderId", orderId);
        String paramString = paramJson.toJSONString();
        String res = HttpUtil.get(appProp.getUrl() + "/pres/getAllWxPresInfo", paramJson.toJavaObject(Map.class));
        System.out.println(">>>>>>>>getPresFromOrderNo-发送数据：" + paramString + " | 时间: " + System.currentTimeMillis());
        System.out.println(">>>>>>>>getPresFromOrderNo-响应数据：" + res + " | 时间: " + System.currentTimeMillis());
        //测试用json字符串
        //res = "{\"data\":[{\"auditPharName\":\"xx\",\"auditTime\":\"2019-03-22 11:00:00\",\"custAge\":\"56岁\",\"custName\":\"56\",\"custSex\":\"1\",\"orderId\":\"order1232\",\"pharName\":\"付俊杰-hn1\",\"presId\":160,\"record\":\"http://www.baidu.com\",\"startTime\":\"2018-8-9 11:00:00\",\"status\":\"B00120001\",\"storeId\":60001,\"syptmFlag\":\"感冒\",\"syptom\":\"\",\"drugList\":[{\"apprNum\":\"国药准字Z45022052\",\"dosage\":\"口服 1次一粒 一天三次\",\"drugCompany\":\"华中药业有限公司\",\"drugErpNo\":\"\",\"drugId\":0,\"drugName\":\"三蛇川贝胶囊\",\"drugNum\":1,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"},{\"apprNum\":\"国药准字Z45022051\",\"dosage\":\"口服 1次一粒 一天二次\",\"drugCompany\":\"新叶药业有限公司\",\"drugErpNo\":\"\",\"drugId\":2,\"drugName\":\"感冒灵\",\"drugNum\":2,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"}]},{\"auditPharName\":\"xx\",\"auditTime\":\"2019-03-22 11:00:00\",\"custAge\":\"56岁\",\"custName\":\"56\",\"custSex\":\"1\",\"orderId\":\"order1232\",\"pharName\":\"付俊杰-hn1\",\"presId\":161,\"record\":\"http://www.baidu.com\",\"startTime\":\"2018-8-9 11:00:00\",\"status\":\"B00120001\",\"storeId\":60001,\"syptmFlag\":\"感冒\",\"syptom\":\"\",\"drugList\":[{\"apprNum\":\"国药准字Z45022052\",\"dosage\":\"口服 1次一粒 一天三次\",\"drugCompany\":\"华中药业有限公司\",\"drugErpNo\":\"\",\"drugId\":0,\"drugName\":\"三蛇川贝胶囊\",\"drugNum\":1,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"},{\"apprNum\":\"国药准字Z45022051\",\"dosage\":\"口服 1次一粒 一天二次\",\"drugCompany\":\"新叶药业有限公司\",\"drugErpNo\":\"\",\"drugId\":2,\"drugName\":\"感冒灵\",\"drugNum\":2,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"}]},{\"auditPharName\":\"xx\",\"auditTime\":\"2019-03-22 11:00:00\",\"custAge\":\"56岁\",\"custName\":\"56\",\"custSex\":\"1\",\"orderId\":\"order1232\",\"pharName\":\"付俊杰-hn1\",\"presId\":162,\"record\":\"http://www.baidu.com\",\"startTime\":\"2018-8-9 11:00:00\",\"status\":\"B00120001\",\"storeId\":60001,\"syptmFlag\":\"感冒\",\"syptom\":\"\",\"drugList\":[{\"apprNum\":\"国药准字Z45022052\",\"dosage\":\"口服 1次一粒 一天三次\",\"drugCompany\":\"华中药业有限公司\",\"drugErpNo\":\"\",\"drugId\":0,\"drugName\":\"三蛇川贝胶囊\",\"drugNum\":1,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"},{\"apprNum\":\"国药准字Z45022051\",\"dosage\":\"口服 1次一粒 一天二次\",\"drugCompany\":\"新叶药业有限公司\",\"drugErpNo\":\"\",\"drugId\":2,\"drugName\":\"感冒灵\",\"drugNum\":2,\"drugUnit\":\"盒\",\"spec\":\"5g*12片\"}]}],\"returnCode\":{\"content\":\"成功\",\"key\":\"C00010000\",\"value\":\"success\"}}";
        //封装返回的jsonString
        JSONObject jsonRes = JSONObject.parseObject(res);
        ReturnCodeDto returnCodeDto = jsonRes.getObject("returnCode", ReturnCodeDto.class);
        List<OrderPresDto> list = new ArrayList<>();
        if("success".equals(returnCodeDto.getValue())) {
            String dataStr = jsonRes.getString("data");
            JSONArray arrData = JSONArray.parseArray(dataStr);
            if(arrData.size() >= 0) {
                list = arrData.toJavaList(OrderPresDto.class);
            }
        }
        return new ResultDto<List>(returnCodeDto, list);
    }

    /**
     * 5.3 连锁在售药品下架接口
     * @param erpids 要下架的ERP编号数组
     * @return
     */
    public String unloadDrugList(List<String> erpids) throws Exception{
        JSONObject paramJson = new JSONObject();
        paramJson.put("appid", appProp.getAppid());
        paramJson.put("token", getToken());
        List<Map<String, String>> jsonList = new ArrayList<>();
        JSONArray ja = new JSONArray();
        for(String s : erpids) {
            JSONObject jo = new JSONObject();
            jo.put("ErpId", s);
            ja.add(jo);
        }
        paramJson.put("drugInfo", ja.toJSONString());
        String paramString = paramJson.toJSONString();
        String res = HttpUtil.post(appProp.getUrl() + "/unloadDrug/chain", paramString);
        System.out.println(">>>>>>>>unloadDrugList-发送数据：" + paramString + " | 时间: " + System.currentTimeMillis());
        System.out.println(">>>>>>>>unloadDrugList-响应数据：" + res + " | 时间: " + System.currentTimeMillis());
        return res;
    }

    /**
     * 5.2 连锁在售药品清单上传
     * @param list 单次调用最大数量限制为50条
     * @return
     */
    public String uploadDrugList(List<DrugUploadDto> list){
        JSONObject paramJson = new JSONObject();
        paramJson.put("appid", appProp.getAppid());
        paramJson.put("token", getToken());
        paramJson.put("drugInfo", JSONObject.toJSONString(list));
        String paramString = paramJson.toJSONString();
        String res = HttpUtil.post(appProp.getUrl() + "/drug/chain", paramString);
        System.out.println(">>>>>>>>uploadDrugList-发送数据：" + paramString + " | 时间: " + System.currentTimeMillis());
        System.out.println(">>>>>>>>uploadDrugList-响应数据：" + res + " | 时间: " + System.currentTimeMillis());
        return res;
    }

    /**
     * 5.10 生成微问诊二维码URL
     * @param qrcodeDto
     * @return
     */
    public String getQrCode(QrcodeDto qrcodeDto) {
        qrcodeDto.setAppid(appProp.getAppid());
        qrcodeDto.setToken(getToken());
        String paramString = JSONObject.toJSONString(qrcodeDto);
        String res = HttpUtil.post(appProp.getUrl()+"/code/getQrcode", paramString);
        System.out.println(">>>>>>>>getQrCode-发送数据：" + paramString + " | 时间: " + System.currentTimeMillis());
        System.out.println(">>>>>>>>getQrCode-响应数据：" + res + " | 时间: " + System.currentTimeMillis());
        return res;
    }

    /**
     * 获得token
     * @return
     */
    public String getToken() {
        if (StrUtil.isBlank(TOKEN)) {
            TOKEN = createToken();
        }
        return TOKEN;
    }

    /**
     * 5.1 调用接口创建token
     * @return
     */
    public String createToken(){
        String url = appProp.getUrl() + "/verify/token";
        String appid = appProp.getAppid();
        String flag = appProp.getFlag();
        String secret = appProp.getSecret();
        Long now = System.currentTimeMillis() / 1000;
        String sign = createSign(appid, flag, secret, Convert.toStr(now));

        //拼装参数
        JSONObject data = new JSONObject();
        data.put("appid", appid);
        data.put("flag", flag);
        data.put("timestamp", now);
        data.put("sign", sign);
        //调用接口获取token
        String res = HttpUtil.get(url, data.toJavaObject(data, Map.class));
        System.out.println(">>>>>>>>>>>调用接口获取token返回：" + res);
        //拆分参数，拿到token
        JSONObject reData = JSONObject.parseObject(res);
        JSONObject returnCode = reData.getJSONObject(WwzUtil.RETURN_CODE);
        if(!"success".equals(returnCode.getString("value"))) {
            //获取token失败返回空串
            return "";
        } else {
            //获得token成功返回token
            JSONObject jsonData = reData.getJSONObject("data");
            //获取token
            String token = jsonData.getString("token");
            return token;
        }
    }

    /**
     * 创建并返回签名
     * @param appid
     * @param flag
     * @param secret
     * @param timestamp
     * @return
     */
    public String createSign(String appid, String flag, String secret, String timestamp) {
        StringBuffer s = new StringBuffer();
        s.append("appid").append("=").append(appid);
        s.append("&flag").append("=").append(flag);
        s.append("&secret").append("=").append(secret);
        s.append("&timestamp").append("=").append(timestamp);
        //MD5签名
        String sign =MD5.MD(s.toString());
        return sign;
    }
}
